/* display.c, Ait, BSD 3-Clause, Kevin Bloom, 2023,
   Derived from: Atto January 2017
   Derived from: Anthony's Editor January 93
*/
#include "header.h"
#include "util.h"
#define TB_IMPL
#include "termbox.h"

int moving_past = FALSE;

/* Reverse scan for start of logical line containing offset */
point_t lnstart(buffer_t *bp, register point_t off)
{
  register char_t *p;
  do
    p = ptr(bp, --off);
  while (bp->b_buf < p && *p != '\n');
  return (bp->b_buf < p ? ++off : 0);
}

/* Forward scan for start of logical line segment (corresponds to screen line)  containing 'finish' */
point_t segstart(buffer_t *bp, window_t *wp, point_t start, point_t finish)
{
  char_t *p;
  int c = 0;
  point_t scan = start;

  while (scan < finish) {
    p = ptr(bp, scan);
    if (*p == '\n') {
      c = 0;
      start = scan + 1;
    } else if (wp->w_cols <= c) {
      c = 0;
      start = scan;
    }
    scan += utf8_size(*ptr(bp,scan));
    c += *p == '\t' ? 8 - (c & 7) : 1;
  }
  return (c < wp->w_cols ? start : finish);
}

/* Forward scan for start of logical line segment following 'finish' */
point_t segnext(buffer_t *bp, window_t *wp, point_t start, point_t finish)
{
  char_t *p;
  int c = 0;

  point_t scan = segstart(bp, wp, start, finish);
  for (;;) {
    p = ptr(bp, scan);
    if (bp->b_ebuf <= p || wp->w_cols <= c)
      break;
    scan += utf8_size(*ptr(bp,scan));
    if (*p == '\n')
      break;
    c += *p == '\t' ? 8 - (c & 7) : 1;
  }
  return (p < bp->b_ebuf ? scan : pos(bp, bp->b_ebuf));
}

/* Move up one screen line */
point_t upup(buffer_t *bp, window_t *wp, point_t off)
{
  point_t curr = lnstart(bp, off);
  point_t seg = segstart(bp, wp, curr, off);
  if(wp->w_row == wp->w_top)
    moving_past = TRUE;
  if (curr < seg)
    off = segstart(bp, wp, curr, seg-1);
  else
    off = segstart(bp, wp, lnstart(bp,curr-1), curr-1);
  return (off);
}

/* Move down one screen line */
point_t dndn(buffer_t *bp, window_t *wp, point_t off)
{
  if(wp->w_row == wp->w_rows - wp->w_top - 1)
    moving_past = TRUE;
  return (segnext(bp, wp, lnstart(bp,off), off));
}

/* Return the offset of a column on the specified line */
point_t lncolumn(buffer_t *bp, point_t offset, int column)
{
  int c = 0;
  char_t *p;
  while ((p = ptr(bp, offset)) < bp->b_ebuf && *p != '\n' && c < column) {
    c += *p == '\t' ? 4 : 1;
    offset += utf8_size(*ptr(bp,offset));
  }
  return (offset);
}

void display(window_t *wp, int flag)
{
  char_t *p, z, *g;
  int i, j, nch, region = 0, searchlen = strlen(searchtext), b = 0, case_sense = FALSE;
  int trailing_whitespace = FALSE, w = 0, token_type = ID_DEFAULT, color = TB_DEFAULT;
  buffer_t *bp = wp->w_bufp;
  point_t matching_bracket = -1;
  int prow = bp->b_row;

  /* find start of screen, handle scroll up off page or top of file  */
  /* point is always within b_page and b_epage */
  if (bp->b_point < bp->b_page)
    bp->b_page = segstart(bp, wp, lnstart(bp,bp->b_point), bp->b_point);

  /* reframe when scrolled off bottom */
  if (bp->b_reframe == 1 ||
      (bp->b_epage <= bp->b_point && curbp->b_point != pos(curbp, curbp->b_ebuf) &&
       (found_point > 0 || wp->w_rows-1 == wp->w_row - wp->w_top))) {
    bp->b_reframe = 0;
    /* Find end of screen plus one. */
    bp->b_page = dndn(bp, wp, bp->b_point);
    /* if we scroll to EOF we show 1 blank line at bottom of screen */
    if (pos(bp, bp->b_ebuf) <= bp->b_page) {
      bp->b_page = pos(bp, bp->b_ebuf);
      i = wp->w_rows - 1;
    } else {
      i = wp->w_rows - 0;
    }
    /* Scan backwards the required number of lines. */
    while (0 < i--)
      bp->b_page = upup(bp, wp, bp->b_page);
  }

  i = wp->w_top;
  j = wp->w_left;
  bp->b_epage = bp->b_page;
//  TODO: make this efficient
  set_parse_state(bp, bp->b_epage); /* are we in a multline comment ? */

  /* paint screen from top of page until we hit maxline */
  while (1) {
    /* reached point - store the cursor position */
    if (bp->b_point == bp->b_epage) {
      bp->b_row = i;
      bp->b_col = j;
    }
    p = ptr(bp, bp->b_epage);
    nch = 1;
    if (wp->w_top + wp->w_rows <= i || bp->b_ebuf <= p) /* maxline */
      break;
    if(curwp == wp && found_point == -1 && is_bracket(*ptr(bp, bp->b_point), FALSE) && (z = is_bracket(*p, TRUE)) != 0) {
      int dir = (z == '}' || z == ']' || z == ')' || z == '>');
      matching_bracket = find_matching_bracket(bp, wp, dir ? -1 : 1, TRUE);
    }
      nch = utf8_size(*p);
      if(wp == curwp &&
    bp->b_mark != NOMARK &&
         ((bp->b_mark <= bp->b_epage &&
           bp->b_point > bp->b_epage) ||
          (bp->b_point <= bp->b_epage &&
           bp->b_mark > bp->b_epage))
         ) {
        region = 1;
      } else if(matching_bracket >= 0 && bp->b_epage == matching_bracket) {
        region = 1;
      } else if(curwp == wp) {
        if(found_point > 0 &&
           search_dir == 1 &&
           found_point - searchlen <= bp->b_epage &&
           bp->b_epage < found_point)
          region = 1;
        else if(found_point > 0 &&
                search_dir == 2 &&
                found_point + searchlen >= bp->b_epage &&
                bp->b_epage > found_point)
          region = 1;
        else if(found_point > 0 && tolower(searchtext[0]) == tolower(*p) && b == 0) {
      if(isupper(searchtext[0]))
        case_sense = TRUE;
      while(b < searchlen) {
        if(isupper(searchtext[b])) {
          case_sense = TRUE;
          if(searchtext[b] == *(p+b)) {
            region = 1;
          } else {
            region = 0;
            b = 0;
            break;
          }
        } else if (case_sense) {
          if(searchtext[b] == *(p+b)) {
            region = 1;
          } else {
            region = 0;
            b = 0;
            break;
          }
        } else if(!case_sense && searchtext[b] == tolower(*(p+b))) {
          region = 1;
        } else {
          region = 0;
          b = 0;
          break;
        }
        b++;
      }
      b = b < 0 ? 0 : b - 1;
    } else if(b > 0) {
      b--;
      region = 1;
    } else {
          region = 0;
          b = 0;
    }
      }
      if(nch > 1) {
        j++;
        uint32_t uni;
        tb_utf8_char_to_unicode(&uni, (char *)p);
        tb_set_cell(j-1, i, uni, region ? TB_BLACK : TB_DEFAULT, region ? TB_WHITE : TB_DEFAULT);
      } else if(*p < 32 && *p != '\n' && *p != '\t') {
        char ctrl = unctrl(*p);
        tb_set_cell(j, i, '^', TB_RED, region ? TB_WHITE : TB_DEFAULT);
        tb_set_cell(j+1, i, ctrl, TB_RED, region ? TB_WHITE : TB_DEFAULT);
        j += 2;
      } else if (isprint(*p) || *p == '\t' || *p == '\n') {
        /* Figure out if the whitespace is trailing or not. */
        g = ptr(bp, bp->b_epage);
        while(isspace(*p) && *p != '\n' && *g != '\n' && isspace(*(g = ptr(bp, bp->b_epage + w))) && bp->b_point != bp->b_epage + w) {
          if(*g == '\n') {
            trailing_whitespace = TRUE;
            break;
          }
          w++;
        }
        w = 0;
        if(trailing_whitespace && *p != '\t') {
          j++;
          uint32_t uni;
          tb_utf8_char_to_unicode(&uni, (char *)p);
          tb_set_cell(j-1, i, uni, TB_DEFAULT, TB_RED);
        } else if(*p == '\t') {
          j += 4;
          for(int t = 4; t > 0; t--)
            tb_set_cell(j-t, i, 0x2500, TB_RED, region ? TB_WHITE : TB_DEFAULT);
        } else {
          j++;
          uint32_t uni;
          tb_utf8_char_to_unicode(&uni, (char *)p);
          token_type = parse_text(bp, bp->b_epage);
          switch(token_type) {
            case ID_SYMBOL: {
              color = TB_MAGENTA;
              break;
            }
            case ID_DOUBLE_STRING: {
              color = TB_GREEN;
              break;
            }
            case ID_SINGLE_STRING: {
              color = TB_GREEN;
              break;
            }
            case ID_BACK_STRING: {
              color = TB_CYAN;
              break;
            }
            case ID_DIGITS: {
              color = TB_CYAN;
              break;
            }
            case ID_LINE_COMMENT: {
              color = TB_BLUE;
              break;
            }
            case ID_BLOCK_COMMENT: {
              color = TB_BLUE;
              break;
            }
            default: {
              color = TB_DEFAULT;
              break;
            }
          }
            tb_set_cell(j-1, i, uni, region ? TB_BLACK : color, region ? TB_WHITE : TB_DEFAULT);
        }
      }
    trailing_whitespace = FALSE;
    if (*p == '\n'  || wp->w_cols <= j - wp->w_left) {
      j -= wp->w_cols;
      if (j < wp->w_left)
        j = wp->w_left;
      ++i;
    }
    bp->b_epage = bp->b_epage + nch;
  }
  b2w(wp); /* save buffer stuff on window */
  modeline(wp);
  if (wp == curwp && flag) {
    dispmsg();
    tb_set_cursor(bp->b_col, bp->b_row); /* set cursor */
  }
  wp->w_update = FALSE;

  if(bp->b_row == prow && !moving_past) {
    bp->b_pcol = bp->b_col;
    wp->w_pcol = bp->b_col;
  }
  moving_past = FALSE;
}

void modeline(window_t *wp)
{
  int i;
  char lch, mch, och;
  char mltemp[TEMPBUF];
  char *percent = NULL;
  point_t pg = lnstart(curbp, curbp->b_page),
          ebuf = pos(curbp, curbp->b_ebuf);
  float dec = 0.0, mod = 0.0;

  lch = (wp == curwp ? '=' : '-');
  mch = ((wp->w_bufp->b_flags & B_MODIFIED) ? '*' : lch);
  och = ((wp->w_bufp->b_flags & B_OVERWRITE) ? 'O' : lch);

  /* Based on the b_page, determine if you're at the top, bottom or
     somewhere in-between the buffer. If in-between, calculate the
     percentage from the bottom. We round up always because that's
     what Emacs does.
  */
  percent = (char *) malloc(sizeof(char *)*3);
  if(pg == 0) {
    percent = "Top";
  } else if(curbp->b_epage == ebuf) {
    percent = "Bot";
  } else {
    mod = curbp->b_page * 100 % ebuf;
    dec = curbp->b_page * 100.0 / ebuf;
    if(mod != 0)
      dec++;
    sprintf(percent, "%d%%", (int)(dec));
  }

  sprintf(mltemp, "%c%c%c %s %c%c (%d,%d) %c%c %s ",  lch,och,mch, wp->w_bufp->b_bname,
    lch, lch, wp->w_bufp->b_line, wp->w_col - wp->w_left, lch, lch, percent);
  addstrxy(mltemp, wp->w_left, wp->w_top + wp->w_rows, 1);

  for (i = strlen(mltemp); i < wp->w_cols; i++)
    addchxy(lch, i+wp->w_left, wp->w_top + wp->w_rows, 1);
}

void dispmsg()
{
  tb_set_cursor(0, MSGLINE);
  if (msgflag) {
    addstr(msgline);
    msgflag = FALSE;
  }
  clrtoeol(msgline, MSGLINE);
}

void display_prompt_and_response(char *prompt, char *response)
{
  char full[NAME_MAX];
  strcpy(full, prompt);
  strcat(full, response);
  print_to_msgline(prompt);
  /* if we have a value print it and go to end of it */
  if (response[0] != '\0')
    addstr(response);
  clrtoeol(full, MSGLINE);
}

void trim_window(buffer_t *bp, window_t *wp)
{
  point_t page = bp->b_page, ebuf = pos(bp, bp->b_ebuf);
  int complete_line = FALSE;
  for(int r = 0; r < wp->w_rows; r++) {
    complete_line = FALSE;
    for(int c = 0; c < wp->w_cols; c++) {
      char_t *p = page >= bp->b_epage ? (char_t *)"\n" : ptr(bp, page);
      if(*p == '\n' || page >= bp->b_epage) {
        complete_line = TRUE;
        int x = wp->w_left + c, y = wp->w_top +r;
        struct tb_cell *front_wide, *back_wide;
        uint32_t space = page > ebuf && c == 0 ? (uint32_t)'~' : (uint32_t)' ';
        int fg = page > ebuf && c == 0 ? TB_CYAN : TB_DEFAULT;
        int bg = TB_DEFAULT;
        cellbuf_get(&global.front, x, y, &front_wide);
        cellbuf_get(&global.back, x, y, &back_wide);
        send_attr(fg, bg);
        send_char(x, y, space);
        cell_set(front_wide, &space, 1, fg, bg);
        cell_set(back_wide, &space, 1, fg, bg);
       } else {
         if(*p == '\t') {
           page++;
           c += 3;
         } else if(*p < 32) {
           page++;
           c++;
         } else
           page += utf8_size(*p);
       }
    }
    if(complete_line)
      page++;
  }
}

void update_display()
{
  window_t *wp;
  buffer_t *bp;

  bp = curwp->w_bufp;
  bp->b_cpoint = bp->b_point; /* cpoint only ever set here */

  /* only one window */
  if (wheadp->w_next == NULL) {
    display(curwp, TRUE);
    trim_window(curbp, curwp);
    tb_present();
    bp->b_psize = bp->b_size;
    return;
  }

  display(curwp, FALSE); /* this is key, we must call our win first to get accurate page and epage etc */
  trim_window(curbp, curwp);
  if(curwp->w_left != 0)
    for(int i = curwp->w_top; i < curwp->w_rows+curwp->w_top+1; i++)
      tb_set_cell(curwp->w_left - 1, i, '|', TB_WHITE, TB_DEFAULT);


  /* never curwp,  but same buffer in different window or update flag set*/
  for (wp=wheadp; wp != NULL; wp = wp->w_next) {
    if (wp != curwp && (wp->w_bufp == bp || wp->w_update)) {
      w2b(wp);
      for(int i = wp->w_top; i < wp->w_rows+wp->w_top+1; i++)
        tb_set_cell(wp->w_left - 1, i, '|', TB_WHITE, TB_DEFAULT);
      display(wp, FALSE);
//      if(wp->w_bufp == bp || wp->w_update) {
      trim_window(wp->w_bufp, wp);
//      }
    }
  }
  /* now display our window and buffer */
  w2b(curwp);
  dispmsg();
  tb_set_cursor(curwp->w_col, curwp->w_row); /* set cursor for curwp */
  tb_present();
  bp->b_psize = bp->b_size;  /* now safe to save previous size for next time */
}

void w2b(window_t *w)
{
  w->w_bufp->b_point = w->w_point;
  w->w_bufp->b_page = w->w_page;
  w->w_bufp->b_epage = w->w_epage;
  w->w_bufp->b_row = w->w_row;
  w->w_bufp->b_col = w->w_col;
  w->w_bufp->b_pcol = w->w_pcol;
  /* fixup pointers in other windows of the same buffer, if size of edit text changed */
  if (w->w_bufp->b_point > w->w_bufp->b_cpoint) {
    w->w_bufp->b_point += (w->w_bufp->b_size - w->w_bufp->b_psize);
    w->w_bufp->b_page += (w->w_bufp->b_size - w->w_bufp->b_psize);
    w->w_bufp->b_epage += (w->w_bufp->b_size - w->w_bufp->b_psize);
  }
}

void b2w(window_t *w)
{
  w->w_point = w->w_bufp->b_point;
  w->w_page = w->w_bufp->b_page;
  w->w_epage = w->w_bufp->b_epage;
  w->w_row = w->w_bufp->b_row;
  w->w_col = w->w_bufp->b_col;
  w->w_pcol = w->w_bufp->b_pcol;
  w->w_bufp->b_size = (w->w_bufp->b_ebuf - w->w_bufp->b_buf) - (w->w_bufp->b_egap - w->w_bufp->b_gap);
}

/* flag = default answer, FALSE=n, TRUE=y */
int yesno(int flag)
{
  struct tb_event ev;

  tb_present();
  if(tb_poll_event(&ev) != TB_OK) return 0;
  if (ev.ch == '\r' || ev.ch == '\n')
    return (flag);
  return (tolower(ev.ch) == 'y');
}

char yesnomaybeso(char d)
{
  struct tb_event ev;
  tb_present();
  if(tb_poll_event(&ev) != TB_OK) return 0;
  if (ev.ch == '\r' || ev.ch == '\n')
    return (d);
  return tolower(ev.ch);
}


void print_tb(const char *str, int x, int y, uint16_t fg, uint16_t bg)
{
    while (*str) {
        uint32_t uni;
        str += tb_utf8_char_to_unicode(&uni, str);
        tb_set_cell(x, y, uni, fg, bg);
        x++;
    }
}


void printf_tb(int x, int y, uint16_t fg, uint16_t bg, const char *fmt, ...)
{
    char buf[4096];
    va_list vl;
    va_start(vl, fmt);
    vsnprintf(buf, sizeof(buf), fmt, vl);
    va_end(vl);
    print_tb(buf, x, y, fg, bg);
}

void addstr(const char *str)
{
  printf_tb(global.cursor_x, global.cursor_y, TB_DEFAULT, TB_DEFAULT, str);
  tb_set_cursor(global.cursor_x+strlen(str), global.cursor_y);
}

void addch(char c)
{
  printf_tb(global.cursor_x, global.cursor_y, TB_DEFAULT, TB_DEFAULT, "%c", c);
  tb_set_cursor(global.cursor_x+1, global.cursor_y);
}

/*
  Print char at point x,y. If within the region, highlight it.
 */
void addchxy(char c, int x, int y, int region)
{
  int fg = region == 0 ? TB_DEFAULT : TB_BLACK;
  int bg = region == 0 ? TB_DEFAULT : TB_WHITE;
  if(c != '\n' && c != '\r')
    printf_tb(x, y, fg, bg, "%c", c);
  else
    printf_tb(x, y, fg, bg, " ");
}

void addstrxy(char *c, int x, int y, int region)
{
  int fg = region == 0 ? TB_DEFAULT : TB_BLACK;
  int bg = region == 0 ? TB_DEFAULT : TB_WHITE;
  printf_tb(x, y, fg, bg, "%s", c);
}

void clrtoeol(const char *str, int line)
{
  int l = strlen(str);
  int size = COLS-l;
  char blanks[size], entire[COLS];
  if(size == 0) {
    for(int i=0; i<size; i++) {
      entire[i]=' ';
    }
    printf_tb(l, line, TB_DEFAULT, TB_DEFAULT, "%s", entire);
  } else {
    for(int i=0; i<size; i++) {
      blanks[i]=' ';
    }
    printf_tb(l, line, TB_DEFAULT, TB_DEFAULT, "%s", blanks);
  }
}
